package com.ruoyi.basebill.service.impl;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;

import com.ruoyi.basebill.domain.BomCostcalc;
import com.ruoyi.basebill.domain.BomCostcalcentry;
import com.ruoyi.basebill.service.IBomCalcdemandService;
import com.ruoyi.basebill.service.IBomCostcalcService;
import com.ruoyi.basedocument.domain.*;
import com.ruoyi.basedocument.service.*;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.util.BillUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.stream.Collectors;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.basebill.domain.BomCalcdemandentry;
import com.ruoyi.basebill.mapper.BomCalcdemandMapper;
import com.ruoyi.basebill.domain.BomCalcdemand;
import org.springframework.util.CollectionUtils;

/**
 * 测试需求单维护Service业务层处理
 *
 * @author ruoyi
 * @date 2024-09-11
 */
@Service
public class BomCalcdemandServiceImpl implements IBomCalcdemandService {
    @Autowired
    private BomCalcdemandMapper bomCalcdemandMapper;
    @Autowired
    private IBomCostcalcService bomCostcalcService;
    @Autowired
    private IBomSpecialmaterialService bomSpecialmaterialService;
    @Autowired
    private IBomMaterialhalfService bomMaterialhalfService;
    @Autowired
    private BillUtil billUtil;
    @Autowired
    private IBomRawmaterialService bomRawmaterialService;
    @Autowired
    private IBomAsscategoryService bomAsscategoryService;
    @Autowired
    private IBomCategoryService bomCategoryService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 查询测试需求单维护
     *
     * @param fid 测试需求单维护主键
     * @return 测试需求单维护
     */
    @Override
    public BomCalcdemand selectBomCalcdemandByFid(String fid) {
        BomCalcdemand bomCalcdemand = bomCalcdemandMapper.selectBomCalcdemandByFid(fid);
        if(bomCalcdemand!=null){
            bomCalcdemand.setFisbarcode(billUtil.selectFile(bomCalcdemand.getFid()));
        }
        return bomCalcdemand;
    }

    /**
     * 查询测试需求单维护列表
     *
     * @param bomCalcdemand 测试需求单维护
     * @return 测试需求单维护
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<BomCalcdemand> selectBomCalcdemandList(BomCalcdemand bomCalcdemand) {
        String userCategoryLongCode = "";
        try {
            SysUser user = SecurityUtils.getLoginUser().getUser();
            userCategoryLongCode = user.getUserCategoryLongCode();
            if(StringUtils.isBlank(userCategoryLongCode)){
                userCategoryLongCode = "(fcustomizedproducttype in ('超级管理员') or fcustomizedproducttype is null)";
            }else{
                userCategoryLongCode = "(fcustomizedproducttype in ('"+userCategoryLongCode.replace(",","','")+"') or fcustomizedproducttype is null)";
            }
            if(SysUser.isAdmin(user.getUserId())){
                userCategoryLongCode = "(fcustomizedproducttype not in ('超级管理员') or fcustomizedproducttype is null)";
            }
        }catch (Exception e){
            System.out.println("获取用户品类失败:"+e);
            userCategoryLongCode = "(fcustomizedproducttype not in ('超级管理员') or fcustomizedproducttype is null)";
        }
        bomCalcdemand.setFcustomizedproducttype(userCategoryLongCode);
        List<BomCalcdemand> bomCalcdemands = bomCalcdemandMapper.selectBomCalcdemandList(bomCalcdemand);
        for (int i = 0; i < bomCalcdemands.size(); i++) {
            BomCalcdemand bomCostcalc1 = bomCalcdemands.get(i);
            String fcreatorid = bomCostcalc1.getFcreator();
            SysUser sysUser = sysUserService.selectUserByUserName(fcreatorid);
            if(sysUser!=null){
                String nickName = sysUser.getNickName();
                bomCostcalc1.setFcreator(nickName);
            }
        }
        return bomCalcdemands;
    }

    /**
     * 新增测试需求单维护
     *
     * @param bomCalcdemand 测试需求单维护
     * @return 结果
     */
    @Transactional
    @Override
    public int insertBomCalcdemand(BomCalcdemand bomCalcdemand) {
        String userCategoryLongCode = "";
        try {
            SysUser user = SecurityUtils.getLoginUser().getUser();
            userCategoryLongCode = user.getUserCategoryLongCode();
            if(StringUtils.isBlank(userCategoryLongCode)){
                userCategoryLongCode = "";
            }else{
                userCategoryLongCode = "'"+userCategoryLongCode.replace(",","','")+"'";
            }
            if(SysUser.isAdmin(user.getUserId())){
                userCategoryLongCode = "'超级管理员'";
            }
        }catch (Exception e){
            System.out.println("获取用户品类失败:"+e);
            userCategoryLongCode = "";
        }
        String fdescription = bomCalcdemand.getFcustomizedproducttype();
        if (StringUtils.isBlank(fdescription)) {
            fdescription = "";
        }
        String add2 = "'"+ fdescription.replace(",","','")+"'";
        if(!"'超级管理员'".equals(userCategoryLongCode)&&!userCategoryLongCode.contains(add2)){
            throw new RuntimeException("没有操作该品类的权限，请修改品类或联系管理员添加权限");
        }
        String billNumber = billUtil.createBillNumber("CSXQ", "t_bom_calcdemand");
        bomCalcdemand.setNumber(billNumber);
        String username = SecurityUtils.getLoginUser().getUsername();
        bomCalcdemand.setFcreatetime(DateUtils.getNowDate());
        bomCalcdemand.setFcreator(username);
        bomCalcdemand.setCreateBy(username);
        bomCalcdemand.setCreateTime(DateUtils.getNowDate());
        setDeptIdByNumber(bomCalcdemand);
        int rows = bomCalcdemandMapper.insertBomCalcdemand(bomCalcdemand);
        billUtil.insertFile(bomCalcdemand.getFisbarcode(), bomCalcdemand.getFid());
        insertBomCalcdemandentry(bomCalcdemand);
        return rows;
    }

    /**
     * 修改测试需求单维护
     *
     * @param bomCalcdemand 测试需求单维护
     * @return 结果
     */
    @Transactional
    @Override
    public int updateBomCalcdemand(BomCalcdemand bomCalcdemand) {
        String userCategoryLongCode = "";
        try {
            SysUser user = SecurityUtils.getLoginUser().getUser();
            userCategoryLongCode = user.getUserCategoryLongCode();
            if(StringUtils.isBlank(userCategoryLongCode)){
                userCategoryLongCode = "";
            }else{
                userCategoryLongCode = "'"+userCategoryLongCode.replace(",","','")+"'";
            }
            if(SysUser.isAdmin(user.getUserId())){
                userCategoryLongCode = "'超级管理员'";
            }
        }catch (Exception e){
            System.out.println("获取用户品类失败:"+e);
            userCategoryLongCode = "";
        }
        String fdescription = bomCalcdemand.getFcustomizedproducttype();
        if (StringUtils.isBlank(fdescription)) {
            fdescription = "";
        }
        String add2 = "'"+ fdescription.replace(",","','")+"'";
        if(!"'超级管理员'".equals(userCategoryLongCode)&&!userCategoryLongCode.contains(add2)){
            throw new RuntimeException("没有操作该品类的权限，请修改品类或联系管理员添加权限");
        }
        String username = SecurityUtils.getUsername();
        Date nowDate = DateUtils.getNowDate();
        bomCalcdemand.setFlastupdateuserid(username);
        bomCalcdemand.setFlastupdatetime(nowDate);
        bomCalcdemand.setUpdateBy(username);
        bomCalcdemand.setUpdateTime(nowDate);
        setDeptIdByNumber(bomCalcdemand);
        bomCalcdemandMapper.deleteBomCalcdemandentryByFParentID(bomCalcdemand.getFid());
        insertBomCalcdemandentry(bomCalcdemand);
        billUtil.insertFile(bomCalcdemand.getFisbarcode(), bomCalcdemand.getFid());
        return bomCalcdemandMapper.updateBomCalcdemand(bomCalcdemand);
    }

    private void setDeptIdByNumber(BomCalcdemand bomCalcdemand){
        String fboxpackdetail = bomCalcdemand.getFboxpackdetail();
        SysDept sysDept = new SysDept();
        sysDept.setDeptNumber(fboxpackdetail);
        List<SysDept> sysDepts = sysDeptService.selectDeptList2(sysDept);
        if (sysDepts==null||sysDepts.size()==0) {
            throw new RuntimeException("部门状态异常，请调整部门:"+fboxpackdetail);
        }
        bomCalcdemand.setFsubmitdept(sysDepts.get(0).getDeptName());
        bomCalcdemand.setDeptId(sysDepts.get(0).getDeptId());
    }

    /**
     * 批量删除测试需求单维护
     *
     * @param fids 需要删除的测试需求单维护主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteBomCalcdemandByFids(String[] fids) {
        bomCalcdemandMapper.deleteBomCalcdemandentryByFParentIDs(fids);
        return bomCalcdemandMapper.deleteBomCalcdemandByFids(fids);
    }

    /**
     * 删除测试需求单维护信息
     *
     * @param fid 测试需求单维护主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteBomCalcdemandByFid(String fid) {
        bomCalcdemandMapper.deleteBomCalcdemandentryByFParentID(fid);
        return bomCalcdemandMapper.deleteBomCalcdemandByFid(fid);
    }

    /**
     * 新增测试需求单维护分录信息
     *
     * @param bomCalcdemand 测试需求单维护对象
     */
    public void insertBomCalcdemandentry(BomCalcdemand bomCalcdemand) {
        List<BomCalcdemandentry> bomCalcdemandentryList = bomCalcdemand.getBomCalcdemandentryList();
        String fid = bomCalcdemand.getFid();
        if (StringUtils.isNotNull(bomCalcdemandentryList)) {
            List<BomCalcdemandentry> list = new ArrayList<BomCalcdemandentry>();
            for (BomCalcdemandentry bomCalcdemandentry : bomCalcdemandentryList) {
                bomCalcdemandentry.setFparentid(fid);
                list.add(bomCalcdemandentry);
            }
            if (list.size() > 0) {
                bomCalcdemandMapper.batchBomCalcdemandentry(list);
            }
        }
    }

    /**
     * 单据状态操作
     *
     * @param ids 主键
     * @return 结果
     */
    public HashMap optionStatus(String[] ids, String status) {
        HashMap<String, Integer> hashMap = new HashMap<>();
        hashMap.put("data", 0);
        int code = 0;
        for (int i = 0; i < ids.length; i++) {
            BomCalcdemand bomCalcdemand = selectBomCalcdemandByFid(ids[i]);
            if("SAVE".equals(status)){
                String ispush = bomCalcdemand.getIspush()==null?"0":bomCalcdemand.getIspush();
                if("1".equals(ispush)){
                    continue;
                }
            }
            if("SUBMIT".equals(status)){
                List<BomCalcdemandentry> bomCalcdemandentryList = bomCalcdemand.getBomCalcdemandentryList();
                if(bomCalcdemandentryList==null||bomCalcdemandentryList.size()==0){
                    continue;
                }
            }
            bomCalcdemand.setCfstate(status);
            int i1 = bomCalcdemandMapper.updateBomCalcdemand(bomCalcdemand);
            code += i1;
            hashMap.put("data",code);
        }
        return hashMap;
    }

    /**
     * 测试需求单维护下推成本测算
     *
     * @param fids 测试需求单维护集合
     * @return 结果
     */
    @Transactional
    @Override
    public int pushCostCalc(String[] fids) {
        List<BomCostcalc> bomCostcalcList = new ArrayList();
        int rows = 0;
        //获取成本测算的测试需求单的ID,进行查询
        //TODO:一对一
        List<BomCostcalc> existList = bomCostcalcService.selectBomCostcalcListByCalcDemandfids(fids);
        //记录已经下推过的编号
        List<String> exsitNumbers = new ArrayList();
        if (CollectionUtils.isEmpty(existList)) {
            for (String fid : fids) {
                BomCalcdemand bomCalcdemand = selectBomCalcdemandByFid(fid);
                BomCostcalc bomCostcalc = assData(bomCalcdemand);
                bomCostcalcService.insertTBomCostcalc(bomCostcalc);
                bomCostcalcList.add(bomCostcalc);
                bomCalcdemand.setIspush("1");
                updateBomCalcdemand(bomCalcdemand);
            }
        } else {
            List<String> exist_coll = existList.stream().map(e -> e.getCfcalcdemandid()).collect(Collectors.toList());
            List<String> add_coll = Arrays.stream(fids).filter(fid -> !exist_coll.contains(fid)).collect(Collectors.toList());
            exsitNumbers = Arrays.stream(fids).filter(fid -> exist_coll.contains(fid)).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(exsitNumbers)){
                BomCostcalc bomCostcalc = bomCostcalcService.selectBomCostcalcByCalcDemandfid(exsitNumbers.get(0));
                if(bomCostcalc!=null){
                    throw new ServiceException(StringUtils.format("已存在下游单据:{}", bomCostcalc.getNumber()));
                }
            }
            for (String fid : add_coll) {
                BomCalcdemand bomCalcdemand = selectBomCalcdemandByFid(fid);
                BomCostcalc bomCostcalc = assData(bomCalcdemand);
                bomCostcalcService.insertTBomCostcalc(bomCostcalc);
                bomCostcalcList.add(bomCostcalc);
                bomCalcdemand.setIspush("1");
                updateBomCalcdemand(bomCalcdemand);
            }
        }
//        int rows = bomCostcalcService.batchBomCostcalc(bomCostcalcList);
        return bomCostcalcList.size();
    }

    /**
     * 组装下推数据
     *
     * @param bomCalcdemand 测算需求数据
     * @return BomCostcalc
     */
    public synchronized BomCostcalc assData(BomCalcdemand bomCalcdemand) {
        BomCostcalc bomCostcalc = new BomCostcalc();
        //业务处理
        bomCostcalc.setFcreatorid(bomCalcdemand.getFcreator());
        bomCostcalc.setFcreatetime(DateUtils.getNowDate());
        String billNumber = billUtil.createBillNumber("CBCS", "t_bom_costcalc");
        bomCostcalc.setNumber(billNumber);
        bomCostcalc.setCfcalcdemandid(bomCalcdemand.getFid());//测算需求单ID-外键
        bomCostcalc.setFbizdate(DateUtils.getNowDate());//业务日期
        bomCostcalc.setCfcustomerid(bomCalcdemand.getFcustomername());//客户
        bomCostcalc.setCfmaterialid(bomCalcdemand.getFmaterialnumber());//产品编码
        bomCostcalc.setCfmaterialname(bomCalcdemand.getFmaterialname());//产品名称
        bomCostcalc.setCfmodel(bomCalcdemand.getFmodule());//cfmodel 规格
        bomCostcalc.setCfbaseunit(bomCalcdemand.getFheadquartersnumber());//cfbaseunit 计量单位
        bomCostcalc.setCftaxrate(bomCalcdemand.getTaxrate());//cfprojecttxt 税率
        bomCostcalc.setCfseasontypeid(bomCalcdemand.getCfseasontypeid());//cfseasontypeid 时间类型
        bomCostcalc.setCfwfzbaseid(bomCalcdemand.getCfwfzbaseid());//cfwfzbaseid 基地
        bomCostcalc.setSournumber(bomCalcdemand.getNumber());//来源单据编码
        bomCostcalc.setIstopbill("1");//是否存在上游单据
        bomCostcalc.setCfstate("SAVE");//状态
        bomCostcalc.setCfremarktxt(bomCalcdemand.getRemark());//备注
        bomCostcalc.setDeptName(bomCalcdemand.getFsubmitdept());//部门名称
        bomCostcalc.setDeptId(bomCalcdemand.getDeptId());//部门id
        bomCostcalc.setFsourcefunction(bomCalcdemand.getFboxpackdetail());//部门编码
        bomCostcalc.setFdescription(bomCalcdemand.getFcustomizedproducttype());//品类
        //组装分录
        List<BomCalcdemandentry> bomCalcdemandentryList = bomCalcdemand.getBomCalcdemandentryList();
        assEntryData(bomCostcalc, bomCalcdemandentryList);

        return bomCostcalc;
    }

    /**
     * 组装成本测算分录
     *
     * @param bomCostcalc            成本测算
     * @param bomCalcdemandentryList 测算需求分录
     */
    private void assEntryData(BomCostcalc bomCostcalc, List<BomCalcdemandentry> bomCalcdemandentryList) {
        //合计材料成本
        BigDecimal totalMaterialCost = new BigDecimal(BigInteger.ZERO);
        //合计成本
        BigDecimal totalCost = new BigDecimal(BigInteger.ZERO);
        //含税成本
        BigDecimal taxCost = new BigDecimal(BigInteger.ZERO);
        //变动费用
        BigDecimal variableCost = new BigDecimal(BigInteger.ZERO);
        //固定费用
        BigDecimal fixedCost = new BigDecimal(BigInteger.ZERO);
        String longcode = "";
        List<BomCostcalcentry> costCalcEntries = new ArrayList<>();
        if (!CollectionUtils.isEmpty(bomCalcdemandentryList)) {
            //需对 bomCalcdemandentryList 进行 BOM拆分；
            for (int i = 0; i < bomCalcdemandentryList.size(); i++) {
                BomCalcdemandentry bomCalcdemandentry = bomCalcdemandentryList.get(i);
                BomCostcalcentry bomCostcalcentry = new BomCostcalcentry();
                //物料属性赋值
                bomCostcalcentry.setCfmaterialhalfnumb(bomCalcdemandentry.getCfproductcode());
                bomCostcalcentry.setCfmaterialhalfname(bomCalcdemandentry.getCfproductname());
                bomCostcalcentry.setCfmaterialhalfunit(bomCalcdemandentry.getCfproductunit());
                if(StringUtils.isNotEmpty(bomCostcalcentry.getCfmaterialhalfnumb())){
                    String cfmaterialhalfnumb = bomCostcalcentry.getCfmaterialhalfnumb();
                    BomSpecialmaterial bomSpecialmaterial = new BomSpecialmaterial();
                    bomSpecialmaterial.setMaterialnumber(cfmaterialhalfnumb);
                    List<BomSpecialmaterial> bomSpecialmaterials = bomSpecialmaterialService.selectBomSpecialmaterialList2(bomSpecialmaterial);
                    if (bomSpecialmaterials!=null&&bomSpecialmaterials.size()!=0) {
                        bomCostcalcentry.setCfrawmaterialid(bomSpecialmaterials.get(0).getGroup4number());
                    }
                }
                //数量
                Long cfquotecount = bomCalcdemandentry.getCfquotecount();
                BigDecimal cfmaterialhalfdose = BigDecimal.valueOf(cfquotecount == null ? 1 : cfquotecount);
                bomCostcalcentry.setCfmaterialhalfdose(cfmaterialhalfdose);
                //历史明细id
                String cfboxgauge = bomCalcdemandentry.getCfboxgauge();
                //长编码
                String cfboxunit = bomCalcdemandentry.getCfboxunit();
                String entryType = StringUtils.isEmpty(bomCalcdemandentry.getCfboxamount()) ? "0" : bomCalcdemandentry.getCfboxamount();
                //类别
                BomAsscategory bomAsscategory = new BomAsscategory();
                bomAsscategory.setMaterialbomnumber(bomCostcalcentry.getCfmaterialhalfnumb());
                List<BomAsscategory> bomAsscategories = bomAsscategoryService.selectBomAsscategoryList2(bomAsscategory);
                if (bomAsscategories.size() != 0&&!"1".equals(entryType)) {
                    String categoryid = bomAsscategories.get(0).getCategoryid();
                    BomCategory bomCategory = bomCategoryService.selectBomCategoryById(categoryid);
                    if(bomCategory!=null){
                        bomCostcalcentry.setCfcategoryid(categoryid);
                        bomCostcalcentry.setCfcategoryname(bomCategory.getName());
                    }
                }
                //判断历史成本测算分录
                if ("1".equals(entryType)) {
                    BomCostcalc bomCostcalc1 = bomCostcalcService.selectTBomCostcalcByFid(cfboxgauge);
                    if (bomCostcalc1 == null) {
                        throw new RuntimeException("引用的历史测算单不存在，请调整后再下推");
                    }
                    bomCostcalcentry.setCfisbomcostcalcdetail(1);
                    bomCostcalcentry.setCfbomcostcalcnumbe("0");
                    bomCostcalcentry.setCfdose(BigDecimal.ONE);
                    bomCostcalcentry.setCfbomcostcalcentryid(cfboxunit);
                    bomCostcalcentry.setCffixationfee(bomCostcalc1.getCffixedfee());
                    bomCostcalcentry.setCfchangefee(bomCostcalc1.getCfalterationfee());
                    List<BomCostcalcentry> bomCostcalcentryList = bomCostcalc1.getBomCostcalcentryList();
                    for (int i1 = 0; bomCostcalcentryList!=null&&i1 < bomCostcalcentryList.size(); i1++) {
                        BomCostcalcentry bomCostcalcentry1 = bomCostcalcentryList.get(i1);
                        bomCostcalcentry1 = bomCostcalcService.removeEntry(bomCostcalcentry1,false, true, true);
                        bomCostcalcentry1.setFid(null);
                        bomCostcalcentry1.setFparentid(null);
                        bomCostcalcentry1.setCfbomcostcalcnumbe("0");
                        bomCostcalcentry1.setCfmaterialhalfdose(bomCostcalcentry1.getCfmaterialhalfdose().multiply(cfmaterialhalfdose));
                        Integer cfisbomcostcalcdetail = bomCostcalcentry1.getCfisbomcostcalcdetail();
                        if(cfisbomcostcalcdetail!=null&&(cfisbomcostcalcdetail==1||cfisbomcostcalcdetail==3)){
                            bomCostcalcentry1.setCfisbomcostcalcdetail(3);
                        }else{
                            bomCostcalcentry1.setCfisbomcostcalcdetail(2);
                        }
                        String cfbomcostcalcentryid1 = bomCostcalcentry1.getCfbomcostcalcentryid();
//                        String cfbomcostcalcentryid = bomCostcalcentry.getCfbomcostcalcentryid() + "," + cfbomcostcalcentryid1;
//                        bomCostcalcentry1.setCfbomcostcalcentryid(cfbomcostcalcentryid);
                        if(!cfbomcostcalcentryid1.contains(",")){
                            longcode += cfbomcostcalcentryid1+",";
                        }
//                        String cfrawmaterialnumbe = bomCostcalcentry1.getCfrawmaterialnumbe();
//                        if (StringUtils.isNotEmpty(cfrawmaterialnumbe)) {
//                            bomCostcalcentry1.setCfrawmaterialnumbe(bomCostcalcentry.getCfbomcostcalcentryid()+","+cfrawmaterialnumbe);
//                        }else{
//                            bomCostcalcentry1.setCfrawmaterialnumbe(bomCostcalcentry.getCfbomcostcalcentryid());
//                        }
                        if(StringUtils.isNotEmpty(bomCostcalcentry1.getCfmaterialhalfnumb())){
                            String cfmaterialhalfnumb = bomCostcalcentry1.getCfmaterialhalfnumb();
                            BomSpecialmaterial bomSpecialmaterial = new BomSpecialmaterial();
                            bomSpecialmaterial.setMaterialnumber(cfmaterialhalfnumb);
                            List<BomSpecialmaterial> bomSpecialmaterials = bomSpecialmaterialService.selectBomSpecialmaterialList2(bomSpecialmaterial);
                            if (bomSpecialmaterials!=null&&bomSpecialmaterials.size()!=0) {
                                bomCostcalcentry1.setCfrawmaterialid(bomSpecialmaterials.get(0).getGroup4number());
                            }
                        }
                        costCalcEntries.add(bomCostcalcentry1);
                    }
                    continue;
                }
                else if("5".equals(entryType)){
                    bomCostcalcentry.setCfbomcostcalcentryid(cfboxunit);
                    bomCostcalcentry.setCfbomcostcalcnumbe("1");
                    bomCostcalcentry.setCfisbomcostcalcdetail(4);
                    BomMaterialhalf bomMaterialhalf = new BomMaterialhalf();
                    bomMaterialhalf.setCfmaterialnumber(bomCostcalcentry.getCfmaterialhalfnumb());
//                    bomMaterialhalf.setCfmaterialname(bomCostcalcentry.getCfmaterialhalfname());
                    List<BomMaterialhalf> bomMaterialhalves = bomMaterialhalfService.selectBomMaterialhalfList2(bomMaterialhalf);
                    if (bomMaterialhalves!=null&&bomMaterialhalves.size()!=0) {
                        BomMaterialhalf bomMaterialhalf1 = bomMaterialhalves.get(0);
                        //BOM用量
                        bomCostcalcentry.setCfdose(bomMaterialhalf1.getCfproductionquantity());
                        bomCostcalcentry.setCfmaterialhalfdose(bomMaterialhalf1.getCfproductionquantity());
                        HashMap materialBomAllNodes = bomCostcalcService.getMaterialBomAllNodes(bomMaterialhalf1.getFid(), cfboxunit);
                        if (materialBomAllNodes.containsKey("reason")) {
                            throw new RuntimeException(materialBomAllNodes.get("reason").toString());
                        }
                        if(materialBomAllNodes.containsKey("list")){
                            ArrayList<BomMaterialhalfentry> list = (ArrayList<BomMaterialhalfentry>)materialBomAllNodes.get("list");
                            if(list==null){
                                bomCostcalc.setIsnewmaterial("1");
                            }
                            for (int i1 = 0; list!=null&&i1 < list.size(); i1++) {
                                BomMaterialhalfentry bomMaterialhalfentry = list.get(i1);
                                BomCostcalcentry bomCostcalcentry1 = new BomCostcalcentry();
                                bomCostcalcentry1.setCfbomcostcalcnumbe("1");
                                bomCostcalcentry1.setCfmaterialhalfnumb(bomMaterialhalfentry.getCfrawmaterialnumbe());
                                bomCostcalcentry1.setCfisbomcostcalcdetail(4);
                                if(StringUtils.isNotEmpty(bomCostcalcentry1.getCfmaterialhalfnumb())){
                                    String cfmaterialhalfnumb = bomCostcalcentry1.getCfmaterialhalfnumb();
                                    BomSpecialmaterial bomSpecialmaterial = new BomSpecialmaterial();
                                    bomSpecialmaterial.setMaterialnumber(cfmaterialhalfnumb);
                                    List<BomSpecialmaterial> bomSpecialmaterials = bomSpecialmaterialService.selectBomSpecialmaterialList2(bomSpecialmaterial);
                                    if (bomSpecialmaterials!=null&&bomSpecialmaterials.size()!=0) {
                                        bomCostcalcentry1.setCfrawmaterialid(bomSpecialmaterials.get(0).getGroup4number());
                                    }
                                }
                                bomCostcalcentry1.setCfmaterialhalfname(bomMaterialhalfentry.getCfrawmaterialname());
                                bomCostcalcentry1.setCfmaterialhalfunit(bomMaterialhalfentry.getCfrawmaterialunit());
                                bomCostcalcentry1.setCfmaterialhalfdose(bomMaterialhalfentry.getCfconsumption());
                                bomCostcalcentry1.setCfdose(bomMaterialhalfentry.getCfconsumption());
                                bomCostcalcentry1.setCfrawmaterialnumbe(bomMaterialhalfentry.getParamnumber());
                                bomCostcalcentry1.setCfbomcostcalcentryid(bomMaterialhalfentry.getLongCode());
                                costCalcEntries.add(bomCostcalcentry1);
                            }
                        }
                    }
                    else{
                        bomCostcalc.setIsnewmaterial("1");
                    }
                }
                else{
                    bomCostcalcentry.setCfbomcostcalcentryid(cfboxunit);
                    bomCostcalcentry.setCfbomcostcalcnumbe(null);
                    bomCostcalcentry.setCfmaterialhalfname(bomCalcdemandentry.getCfproductname());
                    bomCostcalcentry.setCfisbomcostcalcdetail(4);
                }
                //表头金额合计
                costCalcEntries.add(bomCostcalcentry);
            }
        }
        bomCostcalc.setCftotalmaterialcost(totalMaterialCost);//cftotalmaterialcost 合计材料成本
        bomCostcalc.setCftotalcost(totalCost);//cftotalcost 合计成本
        bomCostcalc.setCftaxcost(taxCost);//cftaxcost 含税成本
        bomCostcalc.setCfalterationfee(variableCost);//cfalterationfee 变动费用
        bomCostcalc.setCffixedfee(fixedCost);//cffixedfee 固定费用
        List<BomCostcalcentry> CostEntries = bomCostcalcService.getCostEntries(costCalcEntries);
        BomCostcalc bomCostcalc1 = new BomCostcalc();
        bomCostcalc1.setCfwfzbaseid(bomCostcalc.getCfwfzbaseid());
        bomCostcalc1.setCfseasontypeid(bomCostcalc.getCfseasontypeid());
        bomCostcalc1.setLongCode(longcode);
        bomCostcalc1.setBomCostcalcentryList(CostEntries);
        HashMap hashMap = bomCostcalcService.getBomCoffe(bomCostcalc1);
        if(hashMap.containsKey("list")){
            List<BomCostcalcentry> list = (List<BomCostcalcentry>)hashMap.get("list");
            for (int i = 0; list!=null&&i < list.size(); i++) {
                String cfbomcostcalcentryid = list.get(i).getCfbomcostcalcentryid();
                for (int i1 = 0; i1 < costCalcEntries.size(); i1++) {
                    String cfbomcostcalcentryid1 = costCalcEntries.get(i1).getCfbomcostcalcentryid();
                    if(cfbomcostcalcentryid.equals(cfbomcostcalcentryid1)){
                        costCalcEntries.set(i1,list.get(i));
                        break;
                    }
                }
            }
        }
        List<BomCostcalcentry> rawMaterialEntries = bomCostcalcService.getRawMaterialEntries(costCalcEntries);
        String[] numbers = new String[rawMaterialEntries.size()];
        HashMap<String, String> hashMap1 = new HashMap<>();
        for (int i = 0; i < rawMaterialEntries.size(); i++) {
            numbers[i] = rawMaterialEntries.get(i).getCfmaterialhalfnumb();
            hashMap1.put(rawMaterialEntries.get(i).getCfbomcostcalcentryid(),rawMaterialEntries.get(i).getCfmaterialhalfnumb());
        }
        //引入原材料价格
        HashMap hashMap2 = bomRawmaterialService.introductionPrice(numbers);
        List<BomRawmaterial> list = (List<BomRawmaterial>) hashMap2.get("data");
        for (int i1 = 0; list!=null&&i1 < list.size(); i1++) {
            BomRawmaterial bomRawmaterial = list.get(i1);
            String materialnumber = bomRawmaterial.getMaterialnumber();
            BigDecimal taxrate = bomRawmaterial.getTaxrate();
            BigDecimal price = bomRawmaterial.getPrice();
            for (int i = 0; i < rawMaterialEntries.size(); i++) {
                BomCostcalcentry bomCostcalcentry = rawMaterialEntries.get(i);
                String cfmaterialhalfnumb = bomCostcalcentry.getCfmaterialhalfnumb();
                String cfbomcostcalcentryid = bomCostcalcentry.getCfbomcostcalcentryid();
                if (cfmaterialhalfnumb.equals(materialnumber)&&hashMap1.containsKey(cfbomcostcalcentryid)&&hashMap1.get(cfbomcostcalcentryid).equals(cfmaterialhalfnumb)) {
                    bomCostcalcentry.setCftaxrate(taxrate);
                    bomCostcalcentry.setCftaxprice(price);
                    bomCostcalcentry.setCfdeduction(price);
                }
            }
        }
        for (int i = 0; i < rawMaterialEntries.size(); i++) {
            String cfbomcostcalcentryid = rawMaterialEntries.get(i).getCfbomcostcalcentryid();
            for (int i1 = 0; i1 < costCalcEntries.size(); i1++) {
                String cfbomcostcalcentryid1 = costCalcEntries.get(i1).getCfbomcostcalcentryid();
                if(cfbomcostcalcentryid.equals(cfbomcostcalcentryid1)){
                    costCalcEntries.set(i1,rawMaterialEntries.get(i));
                    break;
                }
            }
        }
        bomCostcalc.setBomCostcalcentryList(costCalcEntries);
    }
}
